
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.spu_serializers import *
from meiduo_admin.paginators import MyPage


class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()


class BrandSimpleView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSimpleModelSerializer


class SPUCateView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = SPUCateModelSerializer

    def get_queryset(self):
        # 路径参数pk得到父级分类id
        parent_id = self.kwargs.get('pk') # 父级分类id or None
        if parent_id: # 如果请求二、三级分类
             # 过滤二级、三级分类查询集
             return self.queryset.filter(parent_id=parent_id)
        else: # 如果请求一级分类
            # 过滤一级分类查询集
            return self.queryset.filter(parent=None)








